<?php

namespace App\Http\Controllers\Backend;


use App\Models\User;
use App\Models\SiteType;
use App\Models\TopicSubscribe;
use App\Models\UserGold;
use App\Models\UserModify;
use App\Models\UserShouting;
use App\Models\UserVerify;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class UserController extends BaseController
{
    protected $list_cache = true;

    // 成员管理
    public function initialize()
    {
        parent::initialize();

        $this->model = 'user';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 列表（需要展示深蓝币）
    // 返回列表数据
    public function lists()
    {
        $where = $this->listWhere();
        $page  = $this->page;
        $rows  = $this->rows;
        $model = $this->checkModel($this->model);
        if($model === false){
            return $this->error($this->error);
        }

        // 模型 和 查询
        if(empty($this->list_cache)){
            $result = $model->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->isCache(true)->listPage($where, $page, $rows, "id DESC");
        }

        // 用户头像，粉丝数量，关注数量，金币数
        if($result['list']){
            $modDb = new UserModify();
            $uids  = array_column($result['list'], 'id');
            $modLi = $modDb->isCache(true)->getListInIds($uids, '*', 'uid');
            $modLi = array_column($modLi, null, 'uid');
            $types = $this->userType(); // 认证类型
            foreach($result['list'] as $key => $item){
                $_uid  = $item['id'];
                $_modi = $modLi[$_uid] ?? [];
                // 整理
                // $result['list'][$key]['apply_type'] = $types[$item['apply_type']]['name'] ?? '';
                $result['list'][$key]['apply_type'] = $item['is_apply'] == 1 ? ($types[$item['apply_type']]['name'] ?? '') : '';
                $result['list'][$key]['head_img']   = $this->getHeadImg($item['head_img']);
                $result['list'][$key]['gold']       = $_modi['gold'] ?? 0;
                $result['list'][$key]['follow_no']  = $_modi['follow_no'] ?? 0;
                $result['list'][$key]['shy_no']     = $_modi['shy_no'] ?? 0;
                $result['list'][$key]['topic_no']   = $_modi['topic_no'] ?? 0;
                $result['list'][$key]['collect_no'] = $_modi['collect_no'] ?? 0;
                $result['list'][$key]['comment_no'] = $_modi['comment_no'] ?? 0;
                $result['list'][$key]['praise_no']  = $_modi['praise_no'] ?? 0;
                $result['list'][$key]['view_no']    = $_modi['view_no'] ?? 0;
                $result['list'][$key]['invite_no']  = $_modi['invite_no'] ?? 0;
            }
        }

        return $this->success($result);
    }

    // 查找
    public function show()
    {
        $itype = $this->getData('show_type', null, 'trim');
        $where = $this->showWhere();
        $model = $this->checkModel($this->model);
        $info  = $model->oneFind($where);
        $this->throwIf($info === false, $model->getError());
        $this->throwIf(empty($info), '你要查看的用户不存在！');

        // 整理
        $info  = $info->toArray();
        $types = $this->userType(); // 认证类型
        // sex job  edu income  industry  work_scope company_type worker_no
        // $info['apply_type'] = $types[$info['apply_type']]['name'] ?? '';
        $info['apply_type'] = $info['is_apply'] == 1 ? ($types[$info['apply_type']]['name'] ?? '') : '';

        // 如果是获取认证信息，只返回特定的几个参数
        if($itype){
            $new = [];
            if($itype == 'auth'){
                $fields = ['id', 'is_apply', 'verify', 'apply_type', 'realname', 'position', 'areas', 'description', 'files', 'links'];
                foreach($fields as $_field){
                    if(in_array($_field, ['areas', 'files', 'links'])){
                        $_value = json_decode($info[$_field], true);
                        $_value = $_value ?: [];
                    } else{
                        $_value = $info[$_field];
                    }

                    $new[$_field] = $_value;
                }
            }

            // 重新定义
            $info = $new;
        }

        return $this->success($info);
    }

    // 启用禁用
    public function status()
    {
        $_value = $this->getData('status', 0, 'intval');
        $this->throwIf(is_null($_value), '是否启用状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1]), '是否启用状态必须为0或1！');

        $id   = $this->id;
        $data = ['status' => $_value, 'uid' => $id];
        // 执行
        $deal   = $this->checkModel($this->model);
        $result = $deal->oneEdit(['id' => $id], $data);
        $this->throwIf($result === false, $deal->getError());

        return $this->success([], '更新成功！');
    }

    // 设置可以后台编辑文章的用户
    public function toEdit()
    {
        $_value = $this->getData('value', 0, 'intval');
        $this->throwIf(is_null($_value), '是否编辑状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1]), '是否编辑状态必须为0或1！');

        $id   = $this->id;
        $data = ['is_edit' => $_value, 'uid' => $id];
        // 执行
        $deal   = $this->checkModel($this->model);
        $result = $deal->oneEdit(['id' => $id], $data);
        $this->throwIf($result === false, $deal->getError());

        return $this->success([], '更新成功！');
    }

    // 订阅话题列表
    public function subscribe()
    {
        $page = $this->page;
        $rows = $this->rows;
        $uid  = $this->getData('id', 0, 'intval');
        $this->throwIf(empty($uid), '请指定查看用户！');

        // 查询
        $model  = new TopicSubscribe();
        $result = $model->getTopic(["uid" => $uid], $page, $rows, "id DESC");

        return $this->success($result);
    }

    // 订阅话题列表
    public function follow()
    {
        $page = $this->page;
        $rows = $this->rows;
        $uid  = $this->getData('id', 0, 'intval');
        $this->throwIf(empty($uid), '请指定查看用户！');

        // 查询
        $model  = new UserShouting();
        $result = $model->getFollow(["uid" => $uid], $page, $rows, "id DESC");

        return $this->success($result);
    }

    // 粉丝
    public function fans()
    {
        $page = $this->page;
        $rows = $this->rows;
        $uid  = $this->getData('id', 0, 'intval');
        $this->throwIf(empty($uid), '请指定查看用户！');

        // 查询
        $model  = new UserShouting();
        $result = $model->getFans(["uid" => $uid], $page, $rows, "id DESC");

        return $this->success($result);
    }

    // 修改密码
    public function password()
    {
        $password = $this->getData('password', '123456', 'trim');

        $data  = ['password' => $password, 'uid' => $this->id,];
        $where = ['id' => $this->id];

        $model = new User();
        $data  = $model->checkData($data, ['id' => $this->id,]);
        $this->throwIf($data === false, $model->getError());

        $result = $model->oneEdit($where, $data);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 添加操作深蓝币
    public function gold()
    {
        $uid   = $this->id;
        $gold  = $this->getData('gold', 0, 'intval');
        $title = $this->getData('reason', null, 'trim');
        $this->throwReturn(empty($uid), '请指定要操作的用户！');
        $this->throwReturn(empty($gold), '请填写要操作的变化金额！');
        $this->throwReturn(empty($title), '请填写操作原因！');
        $this->throwReturn(mb_strlen($title) >= 20, '操作原因不能操作20个字符！');

        // 判断用户金币数量
        $goldDb = new UserGold();
        $modDb  = new UserModify();
        $userDb = new User();
        // 用户信息
        $user   = $userDb->isCache(true)->oneFind(['id' => $uid]);
        $afGold = $user['gold'] + $gold;
        $this->throwReturn($afGold < 0, '用户金币不足！');
        // 用户附件信息 用于删除缓存
        $moInfo = $modDb->isCache(true)->oneFind(['uid' => $uid]);

        // 整理数据
        $data = ['uid' => $uid, 'date' => date('Ymd'), 'title' => $title, 'field' => '', 'price' => $gold,];

        // 保存数据
        $goldDb->fill($data);
        DB::beginTransaction();
        try{
            // 增加用户金币
            $modDb->where('uid', $uid)->update(['gold' => $afGold]);
            // 增加金币记录
            $goldDb->save();
            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 删除缓存
        $goldDb->deleteCacheShow($data);
        $userDb->deleteCacheShow($user);
        $modDb->deleteCacheShow($moInfo);

        return $this->success([], '用户金币操作成功！');
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['status' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表搜索
    protected function listWhere()
    {
        $where    = [['status', '>=', 0]];
        $is_edit  = $this->getData('is_edit', null, 'intval');
        $is_virtu = $this->getData('is_virtual', null, 'intval');
        $is_apply = $this->getData('is_apply', 0, 'intval');
        $from_uid = $this->getData('from_uid', 0, 'intval');
        $mobile   = $this->getData('mobile', null, 'trim');
        $keyword  = $this->getData('keyword', null, 'trim');
        if($keyword){
            $this->list_cache = false;
            $where[] = $this->orWhere('email|nickname|username|position|realname', 'like', $keyword);
            //$where[] = $this->orWhere('username', 'like', "%$keyword%");
        }
        if($mobile){
            $where[] = $this->orWhere('mobile', 'like', "%$mobile%");
            // 不在缓存
            $this->list_cache = false;
        }
        if($from_uid){
            $where[] = $this->orWhere('from_uid', '=', $from_uid);
            // 不在缓存
            $this->list_cache = false;
        }
        if(!is_null($is_virtu)){
            $where[] = ['is_virtual', '=', $is_virtu];
        }
        if(!is_null($is_edit)){
            $where[] = ['is_edit', '=', $is_edit];
        }
        if($is_apply){
            $where[] = ['is_apply', '=', 1];
            $where[] = ['verify', '=', 1];
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $mobile   = $this->getData('mobile', '', 'trim');
        $auth_way = $this->getData('auth_way', 0, 'intval');
        $is_apply = $this->getData('is_apply', 0, 'intval');
        $links    = $this->getData('links', [], 'is_array');
        $files    = $this->getData('files', [], 'is_array');
        $areas    = $this->getData('areas', [], 'is_array');
        $this->throwIf(empty($mobile), '请填写手机号码！');
        $isMobile = preg_match("/^1[3|4|5|6|7|8|9][0-9]\d{8}$/", $mobile);
        $this->throwIf(!$isMobile, '请填写正确手机号!!');
        if($is_apply){
            $this->throwIf(!in_array($auth_way, [1, 2]), '请选择正确的认证方式！');
            if($auth_way == 1){
                $this->throwIf(count($files) != count($files, 1), '请传递正确文件地址！');
                $this->throwIf(count($links) != count($links, 1), '请传递正确网络连接！');
                $this->throwIf(count($areas) != count($areas, 1), '请传递正确网络擅长领域！');
            }
        }

        // 检查手机号是否存在
        $userDb  = new User();
        $yzwhere = [['mobile', '=', $mobile], ['status', '<>', -1]];
        $info    = $userDb->where($yzwhere)->first();
        $this->throwIf($info, '该手机号已经存在！');

        // 组合
        $data = [
            // 'from_uid'     => $this->getData("from_uid"),
            // 'id'           => $this->getData("id"),
            // 'score'        => $this->getData("score"),
            // 'password'     => $this->getData("password"),
            // 'itype'        => $this->getData("itype"),
            // 'channel'      => $this->getData("channel"),
            // 'uid'          => $this->getData("uid"),
            // 'gold'         => $this->getData("gold"),
            // 'last_ip'      => $this->getData("last_ip"),
            // 'last_time'    => $this->getData("last_time"),
            // 'sign'         => $this->getData("sign"),
            // 'phone'        => $this->getData("phone"),

            // 使用
            //'email'        => $this->getData('email', null, 'trim'),
            //'nickname'     => $this->getData("nickname", null, 'trim'),
            //'is_recommend' => $this->getData("is_recommend", 0, 'intval'),
            //'is_index'     => $this->getData("is_index", 0, 'intval'),
            'username'      => $this->getData('username', '', 'trim'),
            'mobile'        => $mobile,
            'head_img'      => $this->getData('head_img', '', 'trim'),
            'sex'           => $this->getData('sex', '0', 'trim'),
            'is_virtual'    => $this->getData("is_virtual", 0, 'intval'),
            'is_edit'       => $this->getData("is_edit", 0, 'intval'),
            'status'        => $this->getData('status', 1, 'intval'),

            // 认证
            'is_apply'      => $is_apply,
            'auth_way'      => $auth_way,
            'verify'        => $is_apply == 1 ? 1 : 0,
            'apply_type'    => $this->getData('apply_type', 0, 'intval'),

            // 个人认证
            'realname'      => $this->getData('realname', '', 'trim'),
            'position'      => $this->getData('position', '', 'trim'),
            'areas'         => $this->jsonChinese($areas),
            'description'   => $this->getData('description', '', 'trim'),
            'files'         => $this->jsonChinese($files),
            'links'         => $this->jsonChinese($links),

            // 组织认证
            'nickname'      => $this->getData('nickname', '', 'trim'),
            'organ_license' => $this->getData('organ_license', '', 'trim'),
            'organ_author'  => $this->getData('organ_author', '', 'trim'),
            'manage_name'   => $this->getData('manage_name', '', 'trim'),
            'manage_job'    => $this->getData('manage_job', '', 'trim'),
            'manage_idcard' => $this->getData('manage_idcard', '', 'trim'),


            // 关联联系方式的字段
            // 'wechat'       => $this->getData("wechat"),
            // 'qq'           => $this->getData("qq"),
            // 'sina'         => $this->getData("sina"),
            // 'apple'        => $this->getData("apple"),

            // 认证操作的字段
            // 'is_apply'    => $this->getData("is_apply"),
            // 'apply_type'  => $this->getData("apply_type"),
            // 'verify'      => $this->getData("verify"),
            // 'address'     => $this->getData("address"),
            // 'city'        => $this->getData("city"),
            // 'position'    => $this->getData("position"),
            // 'files'       => $this->getData("files"),
            // 'links'       => $this->getData("links"),
            // 'areas'       => $this->getData("areas"),
            // 'description' => $this->getData("description"),

            // 'is_auth'    => $this->getData("is_auth"),
            // 'follow_no'  => $this->getData("follow_no"),
            // 'shy_no'     => $this->getData("shy_no"),
            // 'topic_no'   => $this->getData("topic_no"),
            // 'collect_no' => $this->getData("collect_no"),
            // 'comment_no' => $this->getData("comment_no"),
            // 'praise_no'  => $this->getData("praise_no"),
            // 'view_no'    => $this->getData("view_no"),
            // 'invite_no'  => $this->getData("invite_no"),
            // 'fresh_no'   => $this->getData("fresh_no"),
            // 'publish_no' => $this->getData("publish_no"),
            // 'shy_no'     => $this->getData("shy_no"),

            // 'home'             => $this->getData("home"),
            // 'business'         => $this->getData("business"),
            // 'business_summary' => $this->getData("business_summary"),
            // 'company'          => $this->getData("company"),
            // 'department'       => $this->getData("department"),
            // 'certify_type'     => $this->getData("certify_type"),
            // 'certify_code'     => $this->getData("certify_code"),
            // 'invite_code'      => $this->getData("invite_code"),

            // 'dtTime'      => $this->getData("dtTime"),
            // 'dtLast'      => $this->getData("dtLast"),
            // 'idBangDing'  => $this->getData("idBangDing"),
            // 'mediaID'     => $this->getData("mediaID"),
            // 'mediaUserID' => $this->getData("mediaUserID"),
            // 'sIdCard'     => $this->getData("sIdCard"),
            // 'sCard'       => $this->getData("sCard"),
            // 'sCreditCode' => $this->getData("sCreditCode"),
            // 'sLicense'    => $this->getData("sLicense"),
            // 'sLegalName'  => $this->getData("sLegalName"),
            // 'sLegalPhone' => $this->getData("sLegalPhone"),
            // 'sAuthorize'  => $this->getData("sAuthorize"),
            // 'sCheckIn'    => $this->getData("sCheckIn"),
        ];

        // 检查用户名
        if(empty($data['username'])){
            $data['username'] = 'SLH'.$userDb->getAutoInc();
        }

        // 检查唯一性
        //$data = $userDb->checkUser($data);  // 用户名是否重复
        //$this->throwIf($data === false, $userDb->getError());

        // 检查验证 如果是认证用户
        if($is_apply){
            // 个人认证
            if($auth_way == 1){
                $this->throwReturn($data['areas'] == '[]', '请选择擅长的领域！');
                $this->throwReturn($data['files'] == '[]', '请上传证明文件！');
                // 验证信息
                $rules = ["apply_type" => 'required|gt:0', "realname" => 'required', "position" => 'required', "areas" => 'required', "files" => 'required',];
                $msg   = ["apply_type" => '身份类型', "realname" => '真实姓名', "position" => '头衔', "areas" => '擅长领域', "description" => '描述', "files" => '证明文件',];
            } elseif($auth_way == 2){
                // 企业认证
                // 验证信息
                $rules = ["apply_type" => 'required', "nickname" => 'required', "organ_license" => 'required', "organ_author" => 'required', "manage_name" => 'required', "manage_idcard" => 'required', "manage_job" => 'required',];
                $msg   = ["apply_type" => '身份类型', "nickname" => '机构名称', "organ_license" => '营业执照或组织机构证照', "organ_author" => '单位授权证明', "manage_name" => '管理员姓名', "manage_idcard" => '管理者身份证', "manage_job" => '管理员职位',];
            }

            // 执行验证
            $result = $userDb->validator($data, $rules, $msg);
            $this->throwReturn($result === false, $userDb->getError());
        }

        // 审核内容
        $this->baiduTextCensor($data);


        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        // 参数
        $mobile   = $this->getData('mobile', '', 'trim');
        $is_apply = $this->getData('is_apply', 0, 'intval');
        $auth_way = $this->getData('auth_way', 0, 'intval');
        $links    = $this->getData('links', [], 'is_array');
        $files    = $this->getData('files', [], 'is_array');
        $areas    = $this->getData('areas', [], 'is_array');
        $this->throwIf(empty($mobile), '请填写手机号码！');
        $isMobile = preg_match("/^1[3|4|5|6|7|8|9][0-9]\d{8}$/", $mobile);
        $this->throwIf(!$isMobile, '请填写正确手机号!!');
        if($is_apply){
            $this->throwIf(!in_array($auth_way, [1, 2]), '请选择正确的认证方式！');
            if($auth_way == 1){
                $this->throwIf(count($files) != count($files, 1), '请传递正确文件地址！');
                $this->throwIf(count($links) != count($links, 1), '请传递正确网络连接！');
                $this->throwIf(count($areas) != count($areas, 1), '请传递正确网络擅长领域！');
            }
        }

        // 检查手机号是否存在
        $userDb  = new User();
        $yzwhere = [['mobile', '=', $mobile], ['status', '<>', -1], ['id', '<>', $this->id]];
        $info    = $userDb->where($yzwhere)->first();
        $this->throwIf($info, '该手机号已经存在！');

        // 组合
        $data = [
            // 使用
            //'email'        => $this->getData('email', null, 'trim'),
            //'nickname'     => $this->getData("nickname", null, 'trim'),
            //'is_recommend' => $this->getData("is_recommend", 0, 'intval'),
            //'is_index'     => $this->getData("is_index", 0, 'intval'),
            'username'      => $this->getData('username', '', 'trim'),
            'mobile'        => $mobile,
            'head_img'      => $this->getData('head_img', '', 'trim'),
            'sex'           => $this->getData('sex', '0', 'trim'),
            'is_virtual'    => $this->getData("is_virtual", 0, 'intval'),
            'is_edit'       => $this->getData("is_edit", 0, 'intval'),
            //'status'      => $this->getData('status', 1, 'intval'),

            // 认证
            'is_apply'      => $is_apply,
            'verify'        => $is_apply == 1 ? 1 : 0,
            'apply_type'    => $this->getData('apply_type', 0, 'intval'),
            'auth_way'      => $auth_way,

            // 个人认证
            'realname'      => $this->getData('realname', '', 'trim'),
            'position'      => $this->getData('position', '', 'trim'),
            'areas'         => $this->jsonChinese($areas),
            'description'   => $this->getData('description', '', 'trim'),
            'files'         => $this->jsonChinese($files),
            'links'         => $this->jsonChinese($links),

            // 组织认证
            'nickname'      => $this->getData('nickname', '', 'trim'),
            'organ_license' => $this->getData('organ_license', '', 'trim'),
            'organ_author'  => $this->getData('organ_author', '', 'trim'),
            'manage_name'   => $this->getData('manage_name', '', 'trim'),
            'manage_job'    => $this->getData('manage_job', '', 'trim'),
            'manage_idcard' => $this->getData('manage_idcard', '', 'trim'),

        ];

        // 检查唯一性
        //$model = new User();
        //$data  = $model->checkUser($data, $this->id);

        // 检查验证 如果是认证用户
        if($is_apply){
            // 个人认证
            if($auth_way == 1){
                $this->throwReturn($data['areas'] == '[]', '请选择擅长的领域！');
                $this->throwReturn($data['files'] == '[]', '请上传证明文件！');
                // 验证信息
                $rules = ["apply_type" => 'required|gt:0', "realname" => 'required', "position" => 'required', "areas" => 'required', "files" => 'required',];
                $msg   = ["apply_type" => '身份类型', "realname" => '真实姓名', "position" => '头衔', "areas" => '擅长领域', "description" => '描述', "files" => '证明文件',];
            } elseif($auth_way == 2){
                // 企业认证
                // 验证信息
                $rules = ["apply_type" => 'required', "nickname" => 'required', "organ_license" => 'required', "organ_author" => 'required', "manage_name" => 'required', "manage_idcard" => 'required', "manage_job" => 'required',];
                $msg   = ["apply_type" => '身份类型', "nickname" => '机构名称', "organ_license" => '营业执照或组织机构证照', "organ_author" => '单位授权证明', "manage_name" => '管理员姓名', "manage_idcard" => '管理者身份证', "manage_job" => '管理员职位',];
            }

            $result = $userDb->validator($data, $rules, $msg);
            $this->throwReturn($result === false, $userDb->getError());
        }

        // 审核内容
        $this->baiduTextCensor($data);

        return $data;
    }

}


